package com.pablosz.worm.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serializator
{
	public static byte[] serialize(Serializable obj) 
	{
		ByteArrayOutputStream out = null;
		ObjectOutputStream os = null;
		
		try
		{
			out = new ByteArrayOutputStream();
			os = new ObjectOutputStream(out);
			os.writeObject(obj);
			return out.toByteArray();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try
			{
				if( os!=null ) os.close();
				if( out!=null ) out.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		
		return null;
	}
		

	public static Object deserialize(byte[] data)
	{
		ByteArrayInputStream in = null;
		ObjectInputStream is = null;
		
		try
		{
			in = new ByteArrayInputStream(data);
			is = new ObjectInputStream(in);
			return is.readObject();
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if( is!=null ) is.close();
				if( in!=null ) in.close();
			}
			catch (Exception e2)
			{
				e2.printStackTrace();
			}
		}
		
		return null;
	}

}